<template>
	<div>
		<template v-for="(tag, _index) in tags.filter(item => item.checked)" :key="_index">
			<el-tag style="margin-right: 3px;" :closable="!disable" @close="tagClick(tag)">
				{{ tag.name }}
			</el-tag>
		</template>
		<el-button class="button-new-tag ml-1" size="small" @click="drawerTag = true" v-if="!disable">
			标签配置
		</el-button>

		<el-drawer v-model="drawerTag" title="标签选择">
			<template v-for="(tag, _index) in tags" :key="_index">
				<el-tag style="margin: 3px;" type="info" closable @close="remove(tag.id)" :hit="tag.checked"
					@click="tagClick(tag)">
					{{ tag.name }}
				</el-tag>
			</template>
			<el-input v-if="inputVisible" ref="inputRef" v-model="inputValue" class="ml-1 w-20" size="small"
				@keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
			<el-button style="display: inline-block; margin: 7px;" v-else class="button-new-tag ml-1" size="small"
				@click="showInput">
				+ New Tag
			</el-button>
		</el-drawer>
	</div>
</template>
<script setup>
	import {
		ref,
		toRefs,
		nextTick
	} from 'vue';
	import useTags from "./useTags";

	const props = defineProps({
		checks: {
			type: Array,
			default: () => []
		},
		disable: {
			type: Boolean,
			default: false
		}
	})

	const emit = defineEmits(['update:checks'])

	const {
		tags,
		remove,
		check,
		checkTags,
		add,
		addWatchCheck
	} = useTags(props.checks);

	addWatchCheck(val => {
		emit('update:checks', val);
	})

	const inputRef = ref();
	const inputVisible = ref(false);
	const inputValue = ref('');
	const drawerTag = ref(false);

	const showInput = () => {
		inputVisible.value = true;
		nextTick(() => {
			inputRef.value.focus();
		})
	};

	const handleInputConfirm = () => {
		add(inputValue.value);
		inputValue.value = '';
		inputVisible.value = false;
	};

	const tagClick = check;
</script>
